import pyautogui
import time
import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 配置浏览器
def create_browser():
    # 浏览器参数优化
    chrome_options = Options()
    chrome_options.add_argument("--window-size=1920,1080")
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--disable-software-rasterizer")
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--ignore-certificate-errors')
    chrome_options.add_argument('--allow-running-insecure-content')
    chrome_options.add_argument("blink-settings=imagesEnabled=false")
    # browser = webdriver.PhantomJS()
    browser = webdriver.Chrome(options=chrome_options)
    # 需要设置浏览器的window.navigator.webdriver=undefined，不然无法通过滑块检查（速卖通加了webdriver禁止）
    # https://blog.csdn.net/weixin_43881394/article/details/108467118?spm=1005.2026.3001.5635&utm_medium=distribute.pc_relevant_ask_down.none-task-blog-2~default~OPENSEARCH~Rate-5.pc_feed_download_top3ask&depth_1-utm_source=distribute.pc_relevant_ask_down.none-task-blog-2~default~OPENSEARCH~Rate-5.pc_feed_download_top3ask
    # browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    #    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
    # })
    # 最大化
    browser.maximize_window()
    # 最小化
    # browser.minimize_window()
    return browser

def get_orders():
    list = {}
    with open('orders.json') as f:
        list = json.loads(f.read())
    return list


def do_follow(browser,orderNumber):
    print("["+orderNumber+"]开始处理follow")
    while 1:
        start = time.clock()
        try:
            browser.find_element_by_link_text('联系买家').click()
            print('已点击联系买家链接')
            end = time.clock()
            break
        except:
            time.sleep(1)
            print("还未定位到元素!")

    print('定位耗费时间：' + str(end - start))

    handles = browser.window_handles
    # 切换到im tab页
    browser.switch_to_window(handles[1])
    browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
    })
    while 1:
        start = time.clock()
        try:
            browser.find_element_by_class_name("message-fields__autosize")
            print('已定位到元素')
            end = time.clock()
            break
        except:
            time.sleep(1)
            print("还未定位到元素!")

    print('定位耗费时间：' + str(end - start))
    # 找到评价框
    textarea = browser.find_element_by_class_name("message-fields__autosize")
    nextShow = False
    tryCount = 1
    while 1:
        start = time.clock()
        try:
            for i in range(0, 10):
                browser.find_element_by_class_name("button-primiary").click()
                print('已点击下一步')
                nextShow = True
            end = time.clock()
            break
        except:
            if nextShow:
                end = time.clock()
                break
            else:
                if tryCount > 5:
                    break
                time.sleep(1)
                print("还未定位到元素!")
                tryCount = tryCount + 1
    print('点击下一步耗费时间：' + str(end - start))
    text = "Dear friend, \n Please follow my shop, I will thank you very much！\n [Admire]"
    textarea.send_keys(text)
    time.sleep(1)
    js = "var q=document.getElementsByClassName('im-icon-paper-plane')[0].click()"
    browser.execute_script(js)
    # document.getElementsByClassName('im-icon-paper-plane').children[0].click()
    # browser.find_element_by_class_name("im-icon-paper-plane").click()
    time.sleep(2)
    browser.close()
    pass


def do_review(browser,orderNumber):
    print("[" + orderNumber + "]开始处理review")
    # 切回到订单详情页，点击评价，进入评价页
    handles = browser.window_handles
    # 切换到im tab页
    browser.switch_to_window(handles[0])

    while 1:
        start = time.clock()
        try:
            browser.find_element_by_link_text('评价').click()
            print('已点击评价按钮')
            end = time.clock()
            break
        except:
            time.sleep(1)
            print("还未定位到元素!")

    print('定位耗费时间：' + str(end - start))

    handles = browser.window_handles
    # 切换到review tab页
    browser.switch_to_window(handles[1])
    while 1:
        start = time.clock()
        try:
            browser.find_element_by_xpath('//*[@id="the-ratings"]/div/div[3]/span[5]').click()
            print('已点击5星')
            end = time.clock()
            break
        except:
            time.sleep(1)
            print("还未定位到元素!")

    print('定位耗费时间：' + str(end - start))
    # 评价内容
    browser.find_element_by_id('the-form-message').send_keys("You are a good buyer, looking forward to the next cooperation")
    # 点击评价
    browser.find_element_by_id('feedback-submit-button').click()
    browser.close()
    # 3秒后关闭
    handles = browser.window_handles
    # 切换到im tab页
    browser.switch_to_window(handles[0])
    pass


def load_and_get(browser,orderNumber,isLoadCookie):
    url = 'https://gsp.aliexpress.com/apps/order/detail?step=4&orderId=' + orderNumber
    # 打开登录页
    browser.get(url)
    # 没有加载cookie则加载
    if not isLoadCookie:
        # time.sleep(10)
        # 设置cookies跳过登录
        with open('cookies.json') as f:
            listCookies = json.loads(f.read())
        # print('本地cookies:', listCookies)
        for cookie in listCookies:
            if 'sameSite' in cookie:
                del cookie['sameSite']
            browser.add_cookie(cookie)
        isLoadCookie = True
        print("加载登录信息成功")
    # 打开登录页sameSite
    browser.get(url)
    # 读取完cookie刷新页面
    # browser.refresh()
    # 点击联系卖家并发送follow消息
    do_follow(browser,orderNumber)
    # 切回评价页，做评价
    do_review(browser,orderNumber)
    return isLoadCookie

if __name__ == '__main__':
    # 创建流量器
    browser = create_browser()
    # 获取订单列表
    orders = get_orders()
    # 打开地址
    isLoadCookie = False
    for orderNumber in orders:
        s1 = time.clock()
        isLoadCookie = load_and_get(browser,orderNumber,isLoadCookie)
        e1 = time.clock()
        print("[" + orderNumber + "]处理review结束，用时" + str(e1 - s1))
    # 关闭浏览器
    browser.close()








